package com.controller;


import com.aliyuncs.exceptions.ClientException;
import com.constant.MessageConstant;
import com.constant.RedisMessageConstant;
import com.result.Result;
import com.utils.SMSUtils;
import com.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCodes")
public class ValidateCodesController {


    @Autowired
    private JedisPool jedisPool;

    //登录发送验证码
    @PostMapping("/sendLogin")
    public Result sendLogin(String telephone){
        return  send(telephone,RedisMessageConstant.SENDTYPE_LOGIN);
    }

    //预约发送验证码
    @PostMapping("/sendOut")
    public Result sendOut(String telephone){
       return  send(telephone,RedisMessageConstant.SENDTYPE_ORDER);
    }

    public Result send(String telephone,String sendType){
        Jedis jedis = jedisPool.getResource();
        String key=telephone+"_"+ sendType;
        String codeInRedis = jedis.get(key);
        //1.判断生成的key是否已经存在redis数据库中
        if(StringUtils.isEmpty(codeInRedis)){//不存在
            try {
                //2.生成一个4位数的验证码
                Integer code = ValidateCodeUtils.generateValidateCode(4);
                /* //3.阿里云发送验证码(暂时没用)
            try {
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,String.valueOf(code));
            } catch (ClientException e) {
                e.printStackTrace();
                return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
            }*/
                //3.将验证码保存到redis里面
                //jedis.setex(key,60, String.valueOf(code));
                jedis.setex(key,60, String.valueOf(6666));
                return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
            }
        }
        //验证码仍有效，请勿重 复发送验证码！
        return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL_IS_VALID);
    }

}
